// 新增、编辑工单
import type { FormInstance, UploadUserFile } from 'element-plus' // UploadProps UploadFile
import type { ordersUpdateStateType, formOrdersUpdateStateType } from './typings'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { getToken } from '~/utils/auth'
import {
  ElSpace,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElLink,
  ElButton,
  ElMessage,
  ElIcon,
  ElRow,
  ElCol,
  ElTreeSelect,
  ElCard
} from 'element-plus'
import { Plus, WarningFilled } from '@element-plus/icons-vue'
import { handleTrim } from '~/utils/util'
import { SPAN_STYLE_DOUBLE } from '~/utils/const'
import useVuexGetters from '~/hooks/useVuexGetters'
import MapView from '../components/map/MapView' // 地图
import BaseUpload from '~/components/ProForm/BaseUpload' // 上传图片
import SaasTitle from '~/components/SaasTitle'
import styles from '~/pages/oam/index.module.scss'

export default defineComponent({
  name: 'OrdersUpdate',
  props: {
    // 标题
    // 新增工单 传:  "新增工单"
    // 工单列表的编辑工单 传:  "编辑工单"
    // 待办的编辑工单 传:  "编辑工单(待办)"
    title: {
      type: String,
      default: ''
    },
    // 新增、编辑 弹窗是否显示
    showOrdersUpdate: {
      type: Boolean,
      default: false
    },
    // 编辑用 点"查看"获取的那一行的数据
    info: {
      type: Object,
      default: null
    },
    // 是否为来自巡视记录详情的新增
    fromPatrol: {
      type: Object,
      default: null
    },
    cancel: {
      type: Function,
      default: null
    }
  },
  setup(props) {
    const store = useStore()
    const router = useRouter()
    const ruleFormRef = ref<FormInstance>()
    const mapViewRef = ref() // 地图
    const fileList = ref<UploadUserFile[]>([])
    let timer: any = null // 定时器专用timer
    const orderState = useVuexGetters('order', ['deptTreeSelectList']) // 部门
    const { type, id } = router.currentRoute.value.query
    const isRepair = ref(false)
    // 初始值
    // form表单
    const formState = reactive<formOrdersUpdateStateType>({
      form: {
        annexUrl: '',
        repairResource: '',
        repairResourceName: '',
        handleTime: '', // 处理时长 至少为1
        customerName: '', // 客户姓名
        customerPhone: '', // 联系电话
        electrifiedCode: '', // 95598工单号
        defectAddress: '', // 故障地点
        address: '', // 详细地址
        handleDeptId: '', // 指派处理部门
        orderType: '', // 工单紧急程度
        suppleMemo: '', // 报修内容
        orderMemo: '' // 备注
      }
    })

    // 其他值
    const state = reactive<ordersUpdateStateType>({
      elUploadDialogImageUrl: '', // 放大图片 地址
      elUploadDialogVisible: false, // 放大图片的弹窗 是否可见
      loading: false,
      defectAddressSelectList: [],
      actionUrl: '/api/gxsaas-system/oss/endpoint/put-file', // 照片上传
      headers: {
        'gxsaas-Auth': `bearer ${getToken()}`
      },
      orderMarker: true, // 是否为工单地图
      dictionaryOpt: [], // 报修来源
      emergencyOpt: [], // 紧急程度
      ifDisable: true // 默认不填 95598工单号
    })

    onMounted(() => {
      showInfo()
      sourceAjax() // 报修来源下拉选项
      emergencyAjax() // 紧急程度下拉选项
      departmentAjax() // 设备所属部门

      //  巡视记录跳转过来
      if (id || props.info.patrolRecordId) {
        formState.form.handleTime = '24'
        isRepair.value = true
      }
    })

    // methods
    // 编辑 原内容
    const showInfo = () => {
      const editOrder = props.showOrdersUpdate && props.title === '编辑工单'
      const editToDoOrder = props.showOrdersUpdate && props.title === '编辑工单(待办)'
      if (editOrder || editToDoOrder) {
        if (JSON.stringify(props.info) !== '{}') {
          // 原内容
          formState.form = props.info
          formState.form.repairResource = formState.form.repairResourceName
          setTimeout(() => {
            mapViewRef.value.setMarkersByPropsMarkers()
          }, 100)

          // 图片
          if (props.info.annexUrl) {
            fileList.value = []
            const images = props.info.annexUrl.split(',')
            images.map(
              (item: string) =>
                (fileList.value = fileList.value.concat([
                  {
                    name: 'pictureName',
                    url: item
                  }
                ]))
            )
          }
          state.markers = props.info ? { lng: props.info.longitude, lat: props.info.latitude } : {}
        }
      }
    }

    // 报修来源 为'95598报修'时 才能填 95598工单号
    const repairResourceChange = () => {
      getMinNum()
      if (formState.form.repairResourceName === '95598报修') {
        state.ifDisable = false
      } else {
        formState.form.electrifiedCode = '' // 清空刚填的95598工单号
        state.ifDisable = true
      }
    }

    // 联系电话
    const customerPhoneOnInput = () => {
      if (formState.form.customerPhone!.length > 15) {
        formState.form.customerPhone = formState.form.customerPhone!.slice(0, 15)
      }
      formState.form.customerPhone = formState.form.customerPhone?.replace(/[^0-9]/g, '')
    }

    // 处理时长
    const handleTimeOnInput = () => {
      if (
        parseInt(formState.form.handleTime!, 10) > 48 ||
        parseInt(formState.form.handleTime!) < 0
      ) {
        formState.form.handleTime = ''
      }
      formState.form.handleTime = formState.form.handleTime?.replace(/[^\d]/g, '')
    }

    // 附图
    const handleUploadSuccess = (file: Record<string, any>) => {
      const link = file?.data?.link
      if (link) {
        fileList.value?.push(link)
      }
    }

    const handleRemoveUploadFile = (file: Record<string, any>) => {
      const link = file?.url
      // const link = file?.response?.data?.link
      if (link) {
        fileList.value = fileList.value?.filter((item) => item !== link)
      }
    }

    // 故障地点搜索
    const remoteMethod = (value: string) => {
      if (value !== '') {
        state.loading = true
        clearTimeout(timer)
        timer = setTimeout(() => {
          mapViewRef.value.aMapRef.plugin(['AMap.PlaceSearch'], () => {
            const plcceSearch = new mapViewRef.value.aMapRef.PlaceSearch({
              pageIndex: 1, // 页码
              pageSize: 20, // 单页显示结果条数
              city: '武汉'
            })
            plcceSearch.search(value, (status: string, result: Record<string, any>) => {
              // 搜到的数据
              if (status === 'complete' && result.info === 'OK') {
                state.loading = false
                let len = result.poiList.pois.length
                for (let i = 0; i < len; i++) {
                  // 去重
                  for (let j = i + 1; j < len; j++) {
                    if (result.poiList.pois[i].name === result.poiList.pois[j].name) {
                      result.poiList.pois.splice(j, 1)
                      len--
                      j--
                    }
                  }
                }
                state.defectAddressSelectList = result.poiList.pois
              }
            })
          })
        }, 200)
      }
    }

    // 选择后标点
    const addressChange = (value: string) => {
      state.defectAddressSelectList.forEach((item) => {
        if (item.name === value) {
          formState.form.longitude = item.location.lng
          formState.form.latitude = item.location.lat
          state.markers = item.location ? { lng: item.location.lng, lat: item.location.lat } : {}
          const markerTimer = setTimeout(() => {
            mapViewRef.value.setMarkersByPropsMarkers()
            clearTimeout(markerTimer)
          }, 0)
        }
      })
    }

    // 取更小值
    const getMinNum = () => {
      let cfgValueResource = ''
      let cfgValueType = ''
      state.dictionaryOpt.forEach((item) => {
        // 报修来源取值
        if (formState.form.repairResource === item.cfgTypeName) {
          // 初次进入编辑时,字转id,便于取最小值
          formState.form.repairResource = item.id
        }
        if (formState.form.repairResource === item.id) {
          cfgValueResource = item.cfgValue
          formState.form.repairResourceName = item.cfgTypeName
        }
      })
      state.emergencyOpt.forEach((item) => {
        // 紧急程度取值
        if (formState.form.orderType === item.id) {
          cfgValueType = item.cfgValue
          formState.form.orderUrgencyName = item.cfgTypeName
        }
      })

      if (formState.form.repairResource && formState.form.orderType) {
        formState.form.handleTime = Math.min(
          Number(cfgValueResource),
          Number(cfgValueType)
        ).toString()
      } else if (!formState.form.orderType) {
        // 有未定义时
        formState.form.handleTime = Number(cfgValueResource).toString()
      } else if (!formState.form.repairResource) {
        formState.form.handleTime = Number(cfgValueType).toString()
      }
    }

    // 报修来源
    const sourceAjax = async () => {
      const params = {
        current: 1,
        size: 1000,
        cfgTypeCode: 2 // 获取报修来源传2
      }
      const res = await store.dispatch('order/GetOrderSetList', params)
      if (res?.code === 200) {
        state.dictionaryOpt = res.data.records
        //  巡视记录跳转过来
        if (id || props.info.patrolRecordId) {
          state.dictionaryOpt.forEach((item: any) => {
            if (item.cfgTypeName === '巡视上报') {
              formState.form.repairResource = item.id
            }
          })
        }
      }
    }

    //  紧急程度
    const emergencyAjax = async () => {
      const params = {
        current: 1,
        size: 1000,
        cfgTypeCode: 3 // 获取紧急程度传3
      }
      const res = await store.dispatch('order/GetOrderSetList', params)
      if (res?.code === 200) {
        state.emergencyOpt = res.data.records
      }
    }

    // 部门
    const departmentAjax = async () => {
      store.dispatch('order/GetDeptTreeSelectList')
    }

    // 提交
    const submit = (formEl: FormInstance | undefined, ifSend: number) => {
      if (!formEl) return
      formEl.validate((valid) => {
        if (valid) {
          // 去输入的前后空格
          formState.form.customerName = handleTrim(formState.form.customerName ?? '')
          formState.form.customerPhone = handleTrim(formState.form.customerPhone ?? '')
          formState.form.electrifiedCode = handleTrim(formState.form.electrifiedCode ?? '')
          formState.form.address = handleTrim(formState.form.address ?? '')
          formState.form.suppleMemo = handleTrim(formState.form.suppleMemo ?? '')
          formState.form.handleTime = handleTrim(formState.form.handleTime ?? '')
          formState.form.orderMemo = handleTrim(formState.form.orderMemo ?? '')
          //  巡视记录跳转过来需要关联巡视id
          if (id || props.info.patrolRecordId) {
            formState.form.patrolRecordId = id || props.info.patrolRecordId
          }
          // 图片
          if (fileList.value!?.length > 0) {
            formState.form.annexUrl = fileList.value.join(',')
          } else {
            formState.form.annexUrl = ''
          }
          // 报修来源 字转id
          state.dictionaryOpt.forEach((item) => {
            if (formState.form.repairResource === item.cfgTypeName) {
              formState.form.repairResource = item.id
            }
          })
          // 处理时长 传数字
          const realForm = JSON.parse(JSON.stringify(formState.form))
          if (realForm.handleTime) {
            delete realForm.handleTime
          }
          realForm.handleTime = parseInt(formState.form.handleTime!)
          // 传的值与格式
          const element = {
            order: realForm,
            patrolPlanDetailRecord: props.fromPatrol
          }
          if (ifSend === 1) {
            orderAddAjax(element)
          }
          if (ifSend === 2) {
            orderSendOrderAjax(element)
          }
        } else {
          return false
        }
      })
    }

    // 提交请求 保存 编辑
    const orderAddAjax = async (element: Record<string, unknown>) => {
      let res = null
      if (type === 'add') {
        res = await store.dispatch('order/PostOrderAdd', element)
      } else if (props.title === '编辑工单' || props.title === '编辑工单(待办)') {
        // 工单详情那边的编辑 业务
        res = await store.dispatch('order/PostOrderUpdate', formState.form)
      }
      if (res?.code === 200) {
        ElMessage({
          message: '操作成功',
          type: 'success'
        })
        props?.cancel?.()
        // router.go(-1)
      } else {
        ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
      }
    }

    // 保存并发送工单
    const orderSendOrderAjax = async (element: Record<string, unknown>) => {
      const res = await store.dispatch('order/PostSaveAndSendOrder', element)
      if (res?.code === 200) {
        ElMessage({
          type: 'success',
          message: '操作成功!'
        })
        props?.cancel?.()
        // router.go(-1)
      } else {
        ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
      }
    }

    const beforeCloseDialog = () => {
      props?.cancel?.()
      // router.go(-1)
    }

    return () => {
      return (
        <ElCard>
          <ElRow gutter={100} class={styles['ordersUpdate-title']}>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <SaasTitle type="primary">
                <ElLink underline={false} class={styles['order-title']}>
                  基本信息
                </ElLink>
              </SaasTitle>
            </ElCol>
            <ElCol {...SPAN_STYLE_DOUBLE}>
              <SaasTitle type="primary">
                <ElLink underline={false} class={styles['order-title']}>
                  地图
                </ElLink>
              </SaasTitle>
            </ElCol>
          </ElRow>
          <ElRow>
            <ElCol {...SPAN_STYLE_DOUBLE} class={styles['ordersUpdate-form']}>
              <ElForm ref={ruleFormRef} model={formState.form} label-width="120px">
                <ElRow>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem label="客户姓名">
                      <ElInput
                        onInput={() => {
                          if (formState.form.customerName!?.length > 10) {
                            formState.form.customerName = formState.form.customerName?.slice(0, 10)
                          }
                        }}
                        v-model={formState.form.customerName}
                        placeholder="请输入客户姓名"
                        clearable
                      >
                        {{
                          suffix: () => <span>{formState.form.customerName!?.length}/10</span>
                        }}
                      </ElInput>
                    </ElFormItem>
                  </ElCol>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem
                      label="报修来源"
                      prop="repairResource"
                      rules={[{ required: true, message: '请选择报修来源', trigger: 'change' }]}
                    >
                      <ElSelect
                        v-model={formState.form.repairResource}
                        onChange={repairResourceChange}
                        placeholder="请选择报修来源"
                        clearable
                        disabled={isRepair.value}
                      >
                        {state.dictionaryOpt.map((item) => (
                          <ElOption label={item.cfgTypeName} value={item.id}></ElOption>
                        ))}
                      </ElSelect>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElRow>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem label="联系电话">
                      <ElInput
                        v-model={formState.form.customerPhone}
                        placeholder="请输入联系电话"
                        clearable
                        onInput={customerPhoneOnInput}
                      >
                        {{
                          suffix: () => <span>{formState.form.customerPhone!?.length}/15</span>
                        }}
                      </ElInput>
                    </ElFormItem>
                  </ElCol>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem label="95598工单号">
                      <ElInput
                        v-model={formState.form.electrifiedCode}
                        placeholder="报修来源为 '95598报修' 时填写"
                        disabled={state.ifDisable}
                        clearable
                      ></ElInput>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElRow>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem
                      label="指派处理部门"
                      prop="handleDeptId"
                      rules={[
                        { required: true, message: '请选择或输入 部门名称', trigger: 'change' }
                      ]}
                    >
                      <ElTreeSelect
                        v-model={formState.form.handleDeptId}
                        placeholder="请选择或输入 部门名称"
                        data={orderState.deptTreeSelectList.value}
                        checkStrictly // 父级可选
                        clearable
                        props={{
                          label: 'title',
                          value: 'id'
                        }}
                      />
                    </ElFormItem>
                  </ElCol>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem
                      label="工单紧急程度"
                      prop="orderType"
                      rules={[{ required: true, message: '请选择工单紧急程度', trigger: 'change' }]}
                    >
                      <ElSelect
                        v-model={formState.form.orderType}
                        onChange={getMinNum}
                        placeholder="请选择工单紧急程度"
                        clearable
                      >
                        {state.emergencyOpt.map((item) => (
                          <ElOption label={item.cfgTypeName} value={item.id}></ElOption>
                        ))}
                      </ElSelect>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElRow>
                  <ElCol>
                    <ElFormItem
                      label="故障地点"
                      prop="defectAddress"
                      rules={[
                        { required: true, message: '请输入故障地点选择道路', trigger: 'change' }
                      ]}
                    >
                      <ElSelect
                        class={styles['ordersUpdate-defectAddress']}
                        v-model={formState.form.defectAddress}
                        filterable
                        remote
                        reserveKeyword
                        placeholder="请输入故障地点选择道路"
                        remoteMethod={remoteMethod}
                        onChange={addressChange}
                        loading={state.loading}
                        clearable
                      >
                        {state.defectAddressSelectList.map((item) => (
                          <ElOption label={item.name} value={item.name}></ElOption>
                        ))}
                      </ElSelect>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElRow>
                  <ElCol>
                    <ElFormItem label="详细地址">
                      <ElInput
                        onInput={() => {
                          if (formState.form.address!?.length > 40) {
                            formState.form.address = formState.form.address?.slice(0, 40)
                          }
                        }}
                        v-model={formState.form.address}
                        placeholder="请输入详细地址"
                        clearable
                      >
                        {{
                          suffix: () => <span>{formState.form.address!?.length}/40</span>
                        }}
                      </ElInput>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElRow>
                  <ElCol>
                    <ElFormItem
                      class={styles['ordersUpdate-elFormItemRows']}
                      label="报修内容"
                      prop="suppleMemo"
                      rules={[{ required: true, message: '请输入报修内容', trigger: 'change' }]}
                    >
                      <ElInput
                        type="textarea"
                        onInput={() => {
                          if (formState.form.suppleMemo!.length > 100) {
                            formState.form.suppleMemo = formState.form.suppleMemo?.slice(0, 100)
                          }
                        }}
                        v-model={formState.form.suppleMemo}
                        placeholder="请输入报修内容"
                        clearable
                      ></ElInput>
                      <span>{formState.form.suppleMemo!.length}/100</span>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElRow>
                  <ElCol {...SPAN_STYLE_DOUBLE}>
                    <ElFormItem
                      label="计划处理时长"
                      prop="handleTime"
                      rules={[
                        {
                          required: true,
                          message: '请输入计划处理时长(1至48的正整数)',
                          trigger: 'change'
                        }
                      ]}
                    >
                      <ElSpace>
                        <ElInput
                          style={'width: 80%; margin-right: 10px'}
                          v-model={formState.form.handleTime}
                          onInput={handleTimeOnInput}
                          placeholder="请输入1至48的正整数"
                          clearable
                        />
                        <span>小</span>
                        <span>时</span>
                      </ElSpace>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElRow>
                  <ElCol>
                    <ElFormItem class={styles['ordersUpdate-elFormItemRows']} label="备注">
                      <ElInput
                        type="textarea"
                        onInput={() => {
                          if (formState.form.orderMemo!?.length > 100) {
                            formState.form.orderMemo = formState.form.orderMemo?.slice(0, 100)
                          }
                        }}
                        v-model={formState.form.orderMemo}
                        placeholder="请输入备注"
                        clearable
                      ></ElInput>
                      <span>{formState.form.orderMemo!?.length}/100</span>
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElFormItem label="附图">
                  <BaseUpload
                    listType="picture-card"
                    accept=".png,.jpg*"
                    limit={12}
                    fileList={fileList.value?.map?.((item) => ({
                      name: '图片',
                      url: item,
                      response: {
                        data: {
                          link: item
                        }
                      }
                    }))}
                    onSuccess={handleUploadSuccess}
                    onRemove={handleRemoveUploadFile}
                    v-slots={{
                      tip: () => (
                        <section>
                          <ElLink type="info" underline={false} icon={<WarningFilled />}>
                            支持最多上传12张图片
                          </ElLink>
                        </section>
                      )
                    }}
                  >
                    <ElIcon>
                      <Plus />
                    </ElIcon>
                    点击上传
                  </BaseUpload>
                </ElFormItem>
              </ElForm>
            </ElCol>
            <ElCol {...SPAN_STYLE_DOUBLE} class={styles['ordersUpdate-map']}>
              <MapView
                id="ordersUpdateMap"
                ref={mapViewRef}
                markers={state.markers}
                needMultipleMarker={false}
                orderMarker
                clickon
                onChangeAddress={(addressParams) => {
                  formState.form = { ...formState.form, ...addressParams }
                }}
              />
            </ElCol>
          </ElRow>
          <div style={'text-align: right; margin-top: 24px;'}>
            <ElButton plain size="default" onClick={beforeCloseDialog}>
              取 消
            </ElButton>
            <ElButton type="primary" size="default" onClick={() => submit(ruleFormRef.value, 1)}>
              保 存
            </ElButton>
            <ElButton type="primary" size="default" onClick={() => submit(ruleFormRef.value, 2)}>
              保存并发送
            </ElButton>
          </div>
        </ElCard>
      )
    }
  }
})
